package org.ktx.osr.ui

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.window.layout.WindowMetricsCalculator
import org.ktx.osr.service.ScreenRecordingService
import org.ktx.osr.viewmodel.SettingsViewModel

// Data class to hold settings values (replace with your actual data source/ViewModel)
data class AppSettings(
    val resolution: String = "1080p",
    val frameRate: String = "30 fps",
    val videoFormat: String = "MP4",
    val includeSystemSound: Boolean = true,
    val includeMicrophone: Boolean = false,
    val includeCamera: Boolean = false,
    val saveLocation: String = "Internal Storage",
    val showFloatingWidget: Boolean = true
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    onNavigateBack: () -> Unit,
    onStartRecording: () -> Unit,
    onStopRecording: () -> Unit,
) {
    // 使用ViewModel管理设置状态
    val viewModel: SettingsViewModel = viewModel()
    val settings by viewModel.settings.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Settings") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back"
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        SettingsContent(
            modifier = Modifier.padding(paddingValues),
            settings = settings,
            isLoading = isLoading,
            onSettingChange = { newSettings -> viewModel.updateSettings(newSettings) },
            onStartRecording = onStartRecording,
            onStopRecording = onStopRecording
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsContent(
    modifier: Modifier = Modifier,
    settings: AppSettings,
    isLoading: Boolean = false,
    onSettingChange: (AppSettings) -> Unit, // Renamed for clarity
    onStartRecording: () -> Unit,
    onStopRecording: () -> Unit
) {
    val bounds = WindowMetricsCalculator.getOrCreate().computeMaximumWindowMetrics(LocalContext.current).bounds

    // State for managing the bottom sheet visibility and content
    var showBottomSheet by remember { mutableStateOf(false) }
    var bottomSheetTitle by remember { mutableStateOf("") }
    var bottomSheetOptions by remember { mutableStateOf(emptyList<String>()) }
    var currentSettingKey by remember { mutableStateOf<String?>(null) } // To know which setting is being edited

    val sheetState = rememberModalBottomSheetState()

    LaunchedEffect(showBottomSheet) {
        if (!showBottomSheet) sheetState.hide()
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState()) // Added for scrolling
    ) {
        // 显示加载状态
        if (isLoading) {
            Text(
                text = "加载设置中...",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(16.dp)
            )
        }
        // VIDEO
        SettingsGroupTitle("VIDEO")
        SelectableSettingsItem(
            title = "Resolution",
            currentValue = settings.resolution,
            options = listOf("720p", "1080p", "1440p", "原画(${bounds.width()}x${bounds.height()})"),
            onShowBottomSheet = { title, opts ->
                bottomSheetTitle = title
                bottomSheetOptions = opts
                currentSettingKey = "resolution"
                showBottomSheet = true
            }
        )
        SelectableSettingsItem(
            title = "Frame Rate",
            currentValue = settings.frameRate,
            options = listOf("15 fps", "24 fps", "30 fps", "60 fps"), // Example options
            onShowBottomSheet = { title, opts ->
                bottomSheetTitle = title
                bottomSheetOptions = opts
                currentSettingKey = "frameRate"
                showBottomSheet = true
            }
        )
        SelectableSettingsItem(
            title = "Video Format",
            currentValue = settings.videoFormat,
            options = listOf("MP4", "WEBM", ""), // Example options
            onShowBottomSheet = { title, opts ->
                bottomSheetTitle = title
                bottomSheetOptions = opts
                currentSettingKey = "videoFormat"
                showBottomSheet = true
            }
        )

        Spacer(modifier = Modifier.height(24.dp))

        // AUDIO
        SettingsGroupTitle("AUDIO")
        SwitchSettingItem(
            title = "System Sound",
            checked = settings.includeSystemSound && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q,
            enabled = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q,
            onCheckedChange = { onSettingChange(settings.copy(includeSystemSound = it)) }
        )
        SwitchSettingItem(
            title = "Microphone",
            checked = settings.includeMicrophone,
            onCheckedChange = { onSettingChange(settings.copy(includeMicrophone = it)) }
        )
        
        // 添加音频录制说明
        if (settings.includeSystemSound) {
            Text(
                text = "系统音频通过AudioPlaybackCapture捕获，支持Android 10+",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)
            )
        }
        
        // 添加文件保存说明
        Text(
            text = "录制文件将保存在应用专用目录，可通过文件管理器访问",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)
        )

        Spacer(modifier = Modifier.height(24.dp))

        // OTHER
        SettingsGroupTitle("OTHER")
        SwitchSettingItem(
            title = "Camera",
            checked = settings.includeCamera,
            onCheckedChange = { onSettingChange(settings.copy(includeCamera = it)) }
        )
        SwitchSettingItem(
            title = "Show Floating Widget",
            checked = settings.showFloatingWidget,
            onCheckedChange = { onSettingChange(settings.copy(showFloatingWidget = it)) }
        )
        SelectableSettingsItem(
            title = "Save Location", // Corrected title from "Sav..."
            currentValue = settings.saveLocation,
            options = listOf("Internal Storage", "SD Card", "Custom Folder"), // Example options
            onShowBottomSheet = { title, opts ->
                bottomSheetTitle = title
                bottomSheetOptions = opts
                currentSettingKey = "saveLocation"
                showBottomSheet = true
            }
        )

        Spacer(modifier = Modifier.height(24.dp))

        // RECORDING STATUS BUTTON
        // This is a placeholder, actual recording state logic would be more complex
        val recordingState by ScreenRecordingService.recordingStateFlow.collectAsState()
        val isRecording = recordingState == ScreenRecordingService.STATE_RECORDING
        Button(
            onClick = {
                if (isRecording) {
                    onStopRecording()
                } else {
                    onStartRecording()
                }
            },
            modifier = Modifier.fillMaxWidth().height(56.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = if (isRecording) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary
            )
        ) {
            Text(text = if (isRecording) "RECORDING" else "START RECORDING", color = Color.White)
        }
    }



    // Bottom Sheet for options
    if (showBottomSheet) {
        ModalBottomSheet(
            onDismissRequest = { showBottomSheet = false },
            sheetState = sheetState,
            dragHandle = { BottomSheetDefaults.DragHandle() }
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(bottomSheetTitle, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(bottom = 16.dp))
                bottomSheetOptions.forEach { option ->
                    ListItem(
                        headlineContent = { Text(option) },
                        modifier = Modifier.fillMaxWidth().clickable {
                            when (currentSettingKey) {
                                "resolution" -> onSettingChange(settings.copy(resolution = option))
                                // Add cases for other settings like frameRate, videoFormat
                                "frameRate" -> onSettingChange(settings.copy(frameRate = option))
                                "videoFormat" -> onSettingChange(settings.copy(videoFormat = option))
                                "saveLocation" -> onSettingChange(settings.copy(saveLocation = option))
                            }
                            showBottomSheet = false
                        }
                    )
                }
                Spacer(Modifier.height(16.dp))
                Button(onClick = { showBottomSheet = false }, modifier = Modifier.align(Alignment.End)) {
                    Text("Cancel")
                }
                Spacer(Modifier.height(16.dp)) // Ensure content isn't behind navigation bar
            }
        }
    }
}

@Composable
fun SettingsGroupTitle(title: String) {
    Text(
        text = title,
        style = MaterialTheme.typography.labelMedium,
        fontWeight = FontWeight.Bold,
        color = MaterialTheme.colorScheme.onSurfaceVariant,
        modifier = Modifier.padding(bottom = 8.dp)
    )
}

@Composable
fun SelectableSettingsItem(
    title: String,
    currentValue: String,
    options: List<String>,
    onShowBottomSheet: (title: String, options: List<String>) -> Unit
) {
    Card(
        onClick = { onShowBottomSheet("Select $title", options) },
        shape = MaterialTheme.shapes.medium,
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(title, style = MaterialTheme.typography.bodyLarge)
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    text = currentValue,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
                    contentDescription = null, // Or provide a more specific description
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
fun SwitchSettingItem(
    title: String,
    checked: Boolean,
    enabled: Boolean = true,
    onCheckedChange: (Boolean) -> Unit
) {
    Card(
        shape = MaterialTheme.shapes.medium,
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
        modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp), // Adjusted padding for switch
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(title, style = MaterialTheme.typography.bodyLarge)
            Switch(
                checked = checked,
                enabled = enabled,
                onCheckedChange = onCheckedChange,
                colors = SwitchDefaults.colors(
                    checkedThumbColor = MaterialTheme.colorScheme.primary,
                    checkedTrackColor = MaterialTheme.colorScheme.primaryContainer,
                    uncheckedThumbColor = MaterialTheme.colorScheme.outline,
                    uncheckedTrackColor = MaterialTheme.colorScheme.surfaceVariant
                )
            )
        }
    }
}

// Previews
@Preview(showBackground = true)
@Composable
fun SettingsScreenPreviewPortrait() {
    MaterialTheme { // Wrap with your app's theme if needed
        SettingsScreen(onNavigateBack = {}, onStartRecording = {}, onStopRecording = {})
    }
}

@Preview(showBackground = true, widthDp = 720, heightDp = 360)
@Composable
fun SettingsScreenPreviewLandscape() {
    MaterialTheme { // Wrap with your app's theme if needed
        SettingsScreen(onNavigateBack = {}, onStartRecording = {}, onStopRecording = {})
    }
}
